package com.wswy.wzcx.push;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import com.baidu.mobstat.MtjConfig;
import com.blankj.utilcode.util.ActivityUtils;
import com.wswy.wzcx.BuildConfig;
import com.wswy.wzcx.ui.activity.SplashActivity;
import com.wswy.wzcx.ui.main.MainActivity;
import java.util.List;
import timber.log.Timber;

public class RouterActivity extends Activity {


  private static final String EXTRA_VERSION = "version";
  private static final String EXTRA_TARGET = "target";
  private static final String EXTRA_URL = "url";
  private static final String EXTRA_TITLE = "title";
  private static final String EXTRA_USER_CAR_ID = "userCarId";
  private static final String EXTRA_BBS_ID = "bbsId";
  private static final String EXTRA_FINE_NO = "violation";

  private static final String TAG = "RouterActivity";

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    handleStart(getIntent());
  }

  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    handleStart(intent);
  }

  private void handleStart(Intent intent){

    Timber.e("handleStart  -->> "+intent);


    List<Activity> activityList = ActivityUtils.getActivityList();
    //判断是不是冷启动页，只需要判断第一个页面是不是自己
    boolean isAlive = activityList != null && !activityList.isEmpty() && activityList.get(0) != this;

    if (BuildConfig.DEBUG){
      Log.e(TAG, "handleMessage -->activityList "+activityList);
    }

    Intent startIntent = null;

    if (isAlive){
      startIntent = new Intent(this, MainActivity.class);
    }else {
      startIntent = new Intent(this, SplashActivity.class);
    }

    if (intent != null) {
      Uri data = intent.getData();
      try {
        if (data != null) {
          startIntent.putExtra(PushExtras.TARGET, data.getQueryParameter(EXTRA_TARGET));
          startIntent.putExtra(PushExtras.TITLE, data.getQueryParameter(EXTRA_TITLE));
          startIntent.putExtra(PushExtras.URL, data.getQueryParameter(EXTRA_URL));
          startIntent.putExtra(PushExtras.USER_CAR_ID, data.getQueryParameter(EXTRA_USER_CAR_ID));
          startIntent.putExtra(PushExtras.TOPIC_ID, data.getQueryParameter(EXTRA_BBS_ID));
          startIntent.putExtra(PushExtras.FINE_NO, data.getQueryParameter(EXTRA_FINE_NO));
        }
      } catch (Throwable e) {
        e.printStackTrace();
      }
    }


    //启动来源分析
    try {
      startIntent.putExtra(PushExtras.START_FROM,"external");

      startIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
      startActivity(startIntent);

      overridePendingTransition(0,0);
      finish();
    }catch (Throwable e){
      e.printStackTrace();
    }
  }


}
